#!/bin/bash
set -e

# 颜色定义
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m'

# 函数定义
check_container_health() {
    local container_name=$1
    if [ "$(docker container inspect -f '{{.State.Status}}' $container_name 2>/dev/null)" != "running" ]; then
        echo -e "${RED}错误: $container_name 容器未正常运行${NC}"
        return 1
    fi
    return 0
}

# 创建数据目录
echo "创建数据目录..."
mkdir -p data/master data/slave

# 启动 Redis 集群
echo "启动 Redis 集群..."
docker compose up -d

# 等待服务启动（使用循环检查而不是固定等待时间）
echo "等待服务启动..."
for service in redis-master redis-slave redis-sentinel; do
    attempt=1
    max_attempts=30
    while ! check_container_health $service; do
        if [ $attempt -eq $max_attempts ]; then
            echo -e "${RED}错误: $service 服务启动超时${NC}"
            exit 1
        fi
        echo "等待 $service 启动... (尝试 $attempt/$max_attempts)"
        sleep 2
        ((attempt++))
    done
done

# 检查主节点状态
echo -e "\n${GREEN}检查主节点状态...${NC}"
docker exec redis-master redis-cli info | grep role

# 检查主从状态
echo -e "\n${GREEN}检查主从复制状态...${NC}"
docker exec redis-master redis-cli info replication

# 等待从节点同步
echo -e "\n${GREEN}等待从节点同步...${NC}"
attempt=1
max_attempts=10
while true; do
    slave_status=$(docker exec redis-slave redis-cli info replication | grep master_link_status)
    if [[ $slave_status == *"up"* ]]; then
        echo -e "${GREEN}从节点同步成功${NC}"
        break
    fi
    if [ $attempt -eq $max_attempts ]; then
        echo -e "${RED}错误: 从节点同步超时${NC}"
        exit 1
    fi
    echo "等待从节点同步... (尝试 $attempt/$max_attempts)"
    sleep 2
    ((attempt++))
done

# 检查哨兵状态
echo -e "\n${GREEN}检查哨兵状态...${NC}"
docker exec redis-sentinel redis-cli -p 26379 info Sentinel

# 检查哨兵监控的主节点信息
echo -e "\n${GREEN}检查哨兵监控的主节点信息...${NC}"
docker exec redis-sentinel redis-cli -p 26379 sentinel master mymaster

echo -e "\n${GREEN}Redis 高可用集群启动完成！${NC}"
